<?php
/*****************
*版权所有：刘景峰
*联系方式：13810908686
*电子邮件：ljf1279@yeah.net
******************/
class Cache
{
	public $FilePathName;
	public $OverTime;
	public $Content;
	public $DirName;
	public $FileName;
	function __construct($info = null)
	{
		//如果info为文件名
		if(is_string($info))
		{
			$this->FilePathName = $info;
			if(is_file($info))
			{
				$this->Content = file_get_contents($info);
			}
		}
		//分解info
		if(is_array($info))
		{
			foreach($info as $key=>$val)
			{
				if(!is_numeric($key))
					$this->$key = $val;
			}
		}
		if($this->FilePathName)
		{
			//如果文件存在
			if(is_file($this->FilePathName))
			{
				//如果没有设定内容，则从原文件获取
				if(!isset($this->Content))
					$this->Content = file_get_contents($this->FilePathName);
				//转换成绝对路径
				$this->FilePathName = realpath($this->FilePathName);
				//从配置文件获取Cache超时
				if($this->OverTime == '')
				{
					if($conf = $this->getConf('cache.conf'))
					{
						foreach($conf as $key => $val)
						{
							if(realpath($val[filename]) == $this->FilePathName)
							{
								$this->OverTime = $val[overtime];
							}
						}
					}
				}
			}
			$this->DirName = dirname($this->FilePathName);
			$this->FileName = basename($this->FilePathName);
		}
		if($this->OverTime < 10)
		{
			$this->OverTime = 10;
		}
	}
	//更新缓存文件
	function update($Force = false)
	{
		if(is_file($this->FilePathName))
		{
			if($this->OverTime <= (time() - filemtime($this->FilePathName)) || $Force)
			{
				return $this->WriteFile();
			}
		}
		else
		{
			return $this->WriteFile();
		}
	}
	//写文件
	function WriteFile($bOverWrite = true)
	{
		if(!is_dir($this->DirName))
		{
			$this->MakeDir($this->DirName);
		}
		if(!is_dir($this->DirName))
		{
			return false;
		}
		if($bOverWrite)
		{
			if($fp = @fopen($this->FilePathName,"w"))
			{
				fwrite($fp,$this->Content);
				fclose($fp);
				@chmod($this->FilePathName,0777);
				return true;
			}
		}
		return false;
	}
	//递归建立文件夹
	function MakeDir()
	{
		$dir = split('[\/\\]',$this->DirName);
		$strDir = "";
		for($i = 0; $i < count($dir); $i++)
		{
			$strDir .= $dir[$i]."/";
			if($strDir != "/")
			{
				if(!is_dir($strDir))
				{
					@mkdir($strDir,0777);
					@chmod($strDir,0777);
				}
			}
		}
	}

	function getConf($confFileName)
	{
		if(is_file($confFileName))
		{
			$conf = file_get_contents($confFileName);
			return unserialize($conf);
		}
		return false;
	}
	//加载/更新配置项
	static function initConf()
	{
		$sql = "select cachename,fimename,overtime from cache_config";
		
		$conf[$row[cachename]][fimename] = $row[fimename];
		$conf[$row[cachename]][overtime] = $row[overtime];
		
		$strConf = serialize($conf);
	}


}

?>